import { Environment } from "@/environments/environment";
import { AppPluginService } from "@/plugins";
import { IActionService, IViewOpenService, IMsgboxService, IComponentService, IPluginService, IAppCenterService, IAppActionSheetService, AppFuncService, IAppFuncService, ILoadingService, IAppThemeService, IAuthServiceRegister, ICodeListService, ICounterService, IEntityServiceRegister, IUIServiceRegister, IUtilServiceRegister, IViewMessageService, IAppNoticeService, IAppAuthService, } from 'ibz-core';
import { AppBase, removeSessionStorage } from "ibz-core";
import { AuthServiceRegister, CodeListService, CounterService, EntityServiceRegister, IServiceApp, UIServiceRegister, UtilServiceRegister, ViewMessageService } from "ibz-service";
import { AppActionService, IApp } from "ibz-core";
import { AppLoadingService, AppMsgboxService, AppViewOpenService, AppNoticeService, AppCenterService, AppActionSheetService, AppThemeService, AppThirdPartyService, AppAuthService, } from 'ibz-ui-ionic';
import { IAppStorageService, IParam } from "ibz-core";
import { clearCookie, getCookie, setCookie } from "qx-util";
import router from '../../router';
import { AppStorageService } from "./app-storage-service";
import { Register } from "@/register";
import { ComponentService } from './component-service';
import i18n from '../../locale';

export class App extends AppBase implements IApp, IServiceApp {

    /**
     * @description  获取 App 单例对象
     * @static
     * @return {*}  {App}
     * @memberof App
     */
    static getInstance(): App {
        if (!App.App) {
            App.App = new App();
        }
        return this.App;
    }

    /**
     * @description 单例变量声明
     * @private
     * @static
     * @type {App}
     * @memberof App
     */
    private static App: App;

    /**
     * Creates an instance of App.
     * @memberof App
     */
    constructor() {
        super();
        this.initAppLanguage();
        this.initAppTheme();
        this.initPlatFormType();
    }

    /**
     * @description 初始化应用语言
     * @memberof App
     */
    public initAppLanguage() {
        const activeLanguage = localStorage.getItem('activeLanguage');
        if (activeLanguage) {
            this.setActiveLanguage(activeLanguage);
        } else {
            this.setActiveLanguage(i18n.global.locale);
        }
    }

    /**
     * @description 初始化应用主题
     * @memberof App
     */
    public initAppTheme() {
        const appThemeService = AppThemeService.getInstance();
        appThemeService.initAppTheme();
    }

    /**
     * @description 初始化搭载平台
     * @memberof App
     */
    public async initPlatFormType() {
        const appThirdPartyService = AppThirdPartyService.getInstance();
        const platform: any = await appThirdPartyService.getAppPlatform();
        this.setPlatFormType(platform);
    }

    /**
     * @description 获取应用级注册
     * @return {*}  {IParam}
     * @memberof App
     */
    public getUserRegister(): IParam {
        return Register;
    }

    /**
     * @description 获取语言资源i18n
     * @return {*}  {IParam}
     * @memberof App
     */
    public getI18n(): IParam {
        return i18n;
    }

    /**
     * @description 获取UI服务
     * @return {*}  {IUIServiceRegister}
     * @memberof App
     */
    public getUIService(): IUIServiceRegister {
        return UIServiceRegister.getInstance();
    }

    /**
     * @description 获取Auth服务
     * @return {*}  {IAuthServiceRegister}
     * @memberof App
     */
    public getAuthService(): IAuthServiceRegister {
        return AuthServiceRegister.getInstance();
    }

    /**
     * @description 获取Util服务
     * @return {*}  {IUtilServiceRegister}
     * @memberof App
     */
    public getUtilService(): IUtilServiceRegister {
        return UtilServiceRegister.getInstance();
    }

    /**
     * @description 获取实体服务
     * @return {*}  {IEntityServiceRegister}
     * @memberof App
     */
    public getEntityService(): IEntityServiceRegister {
        return EntityServiceRegister.getInstance();
    }

    /**
     * @description 获取代码表服务
     * @return {*}  {ICodeListService}
     * @memberof App
     */
    public getCodeListService(): ICodeListService {
        return new CodeListService();
    }

    /**
     * @description 获取计数器服务
     * @return {*}  {ICounterService}
     * @memberof App
     */
    public getCounterService(): ICounterService {
        return new CounterService();
    }

    /**
     * @description 获取计数器服务
     * @return {*}  {IViewMessageService}
     * @memberof App
     */
    public getViewMSGService(): IViewMessageService {
        return new ViewMessageService();
    }

    /**
     * @description 获取加载服务
     * @return {*}  {ILoadingService}
     * @memberof App
     */
    public getLoadingService(): ILoadingService {
        return AppLoadingService.getInstance();
    }

    /**
     * @description 获取实例化界面行为服务
     * @return {*}  {IActionService}
     * @memberof App
     */
    public getActionService(): IActionService {
        return new AppActionService();
    }

    /**
     * @description 获取应用存储对象
     * @return {*}  {IAppStorageService}
     * @memberof App
     */
    public getStore(): IAppStorageService {
        return AppStorageService.getInstance();
    }

    /**
     * @description 获取视图打开服务
     * @return {*}  {IViewOpenService}
     * @memberof App
     */
    public getOpenViewService(): IViewOpenService {
        return AppViewOpenService.getInstance(router);
    }

    /**
     * @description 获取消息弹框服务
     * @return {*}  {IMsgboxService}
     * @memberof App
     */
    public getMsgboxService(): IMsgboxService {
        return AppMsgboxService.getInstance();
    }

    /**
     * @description 获取消息提示服务
     * @return {*}  {IAppNoticeService}
     * @memberof App
     */
    public getNoticeService(): IAppNoticeService {
        return AppNoticeService.getInstance();
    }

    /**
     * @description 获取组件服务
     * @return {*}  {IComponentService}
     * @memberof App
     */
    public getComponentService(): IComponentService {
        return ComponentService.getInstance();
    }

    /**
     * @description 获取插件服务
     * @return {*}  {IPluginService}
     * @memberof App
     */
    public getPluginService(): IPluginService {
        return AppPluginService.getInstance();
    }

    /**
     * @description 获取应用中心服务
     * @return {*}  {IAppCenterService}
     * @memberof App
     */
    public getCenterService(): IAppCenterService {
        return AppCenterService.getInstance();
    }

    /**
     * @description 获取动作面板服务
     * @return {*}  {IAppActionSheetService}
     * @memberof App
     */
    public getActionSheetService(): IAppActionSheetService {
        return AppActionSheetService.getInstance();
    }

    /** 
     * @description 获取应用功能服务
     * @return {*}  {IAppFuncService}
     * @memberof App
     */
    public getFuncService(): IAppFuncService {
        return AppFuncService.getInstance();
    }

    /** 
     * @description 获取应用主题服务
     * @return {IAppThemeService}  {IAppThemeService}
     * @memberof App
     */
    public getAppThemeService(): IAppThemeService {
        return AppThemeService.getInstance();
    }

    /**
     * @description 获取应用权限服务
     * @return {*}  {IAppAuthService}
     * @memberof App
     */
    public getAppAuthService(): IAppAuthService {
        return AppAuthService.getInstance();
    }

    /**
     * @description 登录
     * @param {{ loginname: string, password: string }} data 登录信息
     * @return {*}  {Promise<IParam>}
     * @memberof App
     */
    public async onLogin(data: { loginname: string, password: string }): Promise<IParam> {
        try {
            this.onClearAppData();
            const response: any = await this.http.post(Environment.RemoteLogin, data, true);
            if (response && response.status === 200) {
                const result = response.data;
                // 设置cookie,保存账号密码7天
                if (result && result.token) {
                    setCookie('ibzuaa-token', result.token, 7, true);
                }
                if (result && result.user) {
                    setCookie('ibzuaa-user', JSON.stringify(result.user), 7, true);
                }
                setCookie('loginname', data.loginname, 7, true);
            }
            return response;
        } catch (error: any) {
            return error;
        }
    }

    /**
     * @description 登出
     * @return {*}  {Promise<any>}
     * @memberof App
     */
    public async onLogout(): Promise<any> {
        try {
            const subscription = this.getMsgboxService().open({ title: '退出登录', content: '你是否确认退出系统' })?.subscribe(async (result: any) => {
                if (result && Object.is(result, 'ok')) {
                    const response: any = await this.http.get(Environment.RemoteLogout);
                    if (response && response.status === 200) {
                        this.onClearAppData();
                        this.goPresetView('login');
                    }
                }
                if (subscription) {
                    subscription.unsubscribe();
                }
                return result;
            })
        } catch (error) {
            console.error(error);
            return null;
        }
    }

    /**
     * @description 清除应用数据
     * @memberof App
     */
    public onClearAppData(): void {
        // 清除user、token
        clearCookie('ibzuaa-token', true);
        clearCookie('ibzuaa-user', true);
        clearCookie('loginname', true);
        // 清除应用级数据
        this.setLocalData(null);
        this.setContext(null);
        this.setAuthResData(null);
        // 清除租户相关信息
        removeSessionStorage("activeOrgData");
        removeSessionStorage("srfdynaorgid");
        removeSessionStorage("dcsystem");
        removeSessionStorage("orgsData");
    }

    /**
     * @description 获取用户信息
     * @return {*}  {IParam}
     * @memberof App
     */
    public getUserInfo(): IParam {
        return JSON.parse(getCookie('ibzuaa-user') as string);
    }

    /**
     * @description 跳转预置视图
     * @param {("login" | "404" | "500")} pageTag
     * @memberof App
     */
    public goPresetView(pageTag: "login" | "404" | "500"): void {
        router.push({ name: pageTag });
    }
}